// pages/chat/chat.js
const { get, post } = require('../../utils/api.js')
const { showError, showSuccess, showToast, formatTime } = require('../../utils/util.js')
const { navigateBack } = require('../../utils/router.js')

Page({
  data: {
    // 用户信息
    userId: '',
    userProfile: null,
    conversationId: '',
    
    // 聊天消息
    messages: [],
    loading: false,
    loadingMore: false,
    hasMore: true,
    
    // 输入相关
    inputMessage: '',
    inputHeight: 60,
    showEmojiPanel: false,
    showVoicePanel: false,
    
    // 语音消息
    isRecording: false,
    recordingTime: 0,
    recordingTimer: null,
    voiceFilePath: '',
    
    // 表情包
    emojiCategories: [
      {
        name: '常用',
        emojis: ['😊', '😂', '😍', '😘', '😋', '😉', '😎', '😜', '🤗', '😇', '🙃', '😅']
      },
      {
        name: '表情',
        emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃']
      },
      {
        name: '手势',
        emojis: ['👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆', '👇']
      },
      {
        name: '爱心',
        emojis: ['❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💔', '❣️', '💕']
      }
    ],
    currentEmojiCategory: 0,
    
    // 破冰话题
    iceBreakerSuggestions: [],
    showIceBreakerPanel: false,
    
    // 聊天状态
    isTyping: false,
    lastReadMessageId: '',
    connectionStatus: 'connected',
    
    // 消息操作
    showMessageMenu: false,
    selectedMessage: null,
    
    // 匹配信息
    matchInfo: null,
    showMatchInfo: false,
    
    // 键盘高度
    keyboardHeight: 0,
    
    // 页面状态
    scrollToBottom: false,
    
    // 用户在线状态
    isUserOnline: false,
    lastSeen: '',
    
    // 消息发送状态
    sendingMessages: new Map()
  },

  onLoad(options) {
    const { userId, conversationId } = options
    
    if (!userId || !conversationId) {
      showError('参数错误')
      navigateBack()
      return
    }
    
    this.setData({
      userId,
      conversationId
    })
    
    this.initPage()
  },

  onShow() {
    // 标记消息为已读
    this.markAllAsRead()
    
    // 开启实时消息监听
    this.startMessageListener()
  },

  onHide() {
    // 停止实时消息监听
    this.stopMessageListener()
  },

  onUnload() {
    // 清理定时器
    if (this.data.recordingTimer) {
      clearInterval(this.data.recordingTimer)
    }
    
    // 停止录音
    if (this.data.isRecording) {
      this.stopRecording()
    }
    
    // 停止消息监听
    this.stopMessageListener()
  },

  /**
   * 键盘高度变化
   */
  onKeyboardHeightChange(e) {
    this.setData({
      keyboardHeight: e.detail.height
    })
    
    // 键盘弹起时滚动到底部
    if (e.detail.height > 0) {
      setTimeout(() => {
        this.scrollToBottom()
      }, 100)
    }
  },

  /**
   * 初始化页面
   */
  async initPage() {
    try {
      // 并行加载用户信息和聊天记录
      await Promise.all([
        this.loadUserProfile(),
        this.loadChatHistory(),
        this.loadMatchInfo(),
        this.loadIceBreakerSuggestions()
      ])
      
      // 滚动到底部
      this.scrollToBottom()
      
    } catch (error) {
      console.error('初始化页面失败:', error)
      showError('加载聊天数据失败')
    }
  },

  /**
   * 加载用户资料
   */
  loadUserProfile() {
    return get(`/api/users/${this.data.userId}/profile`)
      .then(data => {
        this.setData({
          userProfile: data,
          isUserOnline: this.checkOnlineStatus(data.lastActive),
          lastSeen: this.formatLastSeen(data.lastActive)
        })
        
        // 设置导航栏标题
        wx.setNavigationBarTitle({
          title: data.nickname || '聊天'
        })
      })
  },

  /**
   * 加载聊天记录
   */
  loadChatHistory() {
    this.setData({ loading: true })
    
    return get(`/api/messages/${this.data.conversationId}/history`, {
      limit: 20,
      offset: 0
    })
      .then(data => {
        const messages = this.processMessages(data.messages || [])
        
        this.setData({
          messages,
          hasMore: data.hasMore || false,
          loading: false,
          lastReadMessageId: data.lastReadMessageId || ''
        })
      })
      .catch(error => {
        console.error('加载聊天记录失败:', error)
        this.setData({ loading: false })
        throw error
      })
  },

  /**
   * 加载更多聊天记录
   */
  loadMoreHistory() {
    if (this.data.loadingMore || !this.data.hasMore) return
    
    this.setData({ loadingMore: true })
    
    get(`/api/messages/${this.data.conversationId}/history`, {
      limit: 20,
      offset: this.data.messages.length
    })
      .then(data => {
        const newMessages = this.processMessages(data.messages || [])
        
        this.setData({
          messages: [...newMessages, ...this.data.messages],
          hasMore: data.hasMore || false,
          loadingMore: false
        })
      })
      .catch(error => {
        console.error('加载更多聊天记录失败:', error)
        this.setData({ loadingMore: false })
        showError('加载失败，请重试')
      })
  },

  /**
   * 加载匹配信息
   */
  loadMatchInfo() {
    return get(`/api/matches/${this.data.userId}/info`)
      .then(data => {
        this.setData({
          matchInfo: data,
          showMatchInfo: data.isNewMatch || false
        })
      })
      .catch(error => {
        console.error('加载匹配信息失败:', error)
      })
  },

  /**
   * 加载破冰话题建议
   */
  loadIceBreakerSuggestions() {
    return get(`/api/messages/ice-breakers`, {
      userId: this.data.userId,
      conversationId: this.data.conversationId
    })
      .then(data => {
        this.setData({
          iceBreakerSuggestions: data.suggestions || []
        })
      })
      .catch(error => {
        console.error('加载破冰话题失败:', error)
      })
  },

  /**
   * 处理消息数据
   */
  processMessages(messages) {
    const currentUserId = getApp().getUserId()
    
    return messages.map(message => {
      return {
        ...message,
        isSelf: message.senderId === currentUserId,
        timeFormatted: formatTime(message.createdAt),
        showTime: this.shouldShowTime(message, messages),
        status: message.status || 'sent'
      }
    })
  },

  /**
   * 判断是否显示时间
   */
  shouldShowTime(currentMessage, allMessages) {
    const currentIndex = allMessages.findIndex(msg => msg.id === currentMessage.id)
    
    if (currentIndex === 0) return true
    
    const prevMessage = allMessages[currentIndex - 1]
    const timeDiff = new Date(currentMessage.createdAt) - new Date(prevMessage.createdAt)
    
    // 超过5分钟显示时间
    return timeDiff > 5 * 60 * 1000
  },

  /**
   * 发送文本消息
   */
  sendTextMessage() {
    const message = this.data.inputMessage.trim()
    
    if (!message) {
      showToast('请输入消息内容')
      return
    }
    
    this.sendMessage({
      type: 'text',
      content: message
    })
    
    this.setData({ inputMessage: '' })
  },

  /**
   * 发送表情消息
   */
  sendEmojiMessage(e) {
    const emoji = e.currentTarget.dataset.emoji
    
    this.sendMessage({
      type: 'emoji',
      content: emoji
    })
    
    this.hideEmojiPanel()
  },

  /**
   * 发送语音消息
   */
  sendVoiceMessage(filePath, duration) {
    this.sendMessage({
      type: 'voice',
      content: filePath,
      duration: duration
    })
  },

  /**
   * 发送破冰话题
   */
  sendIceBreaker(e) {
    const suggestion = e.currentTarget.dataset.suggestion
    
    this.sendMessage({
      type: 'text',
      content: suggestion
    })
    
    this.hideIceBreakerPanel()
  },

  /**
   * 通用发送消息方法
   */
  sendMessage(messageData) {
    const tempId = 'temp_' + Date.now()
    const currentUserId = getApp().getUserId()
    
    // 创建临时消息
    const tempMessage = {
      id: tempId,
      type: messageData.type,
      content: messageData.content,
      senderId: currentUserId,
      receiverId: this.data.userId,
      conversationId: this.data.conversationId,
      createdAt: new Date().toISOString(),
      isSelf: true,
      status: 'sending',
      timeFormatted: formatTime(new Date()),
      showTime: true,
      duration: messageData.duration || 0
    }
    
    // 添加到消息列表
    this.setData({
      messages: [...this.data.messages, tempMessage]
    })
    
    // 滚动到底部
    this.scrollToBottom()
    
    // 发送到服务器
    post('/api/messages/send', {
      conversationId: this.data.conversationId,
      receiverId: this.data.userId,
      type: messageData.type,
      content: messageData.content,
      duration: messageData.duration
    })
      .then(response => {
        // 更新消息状态
        const messages = this.data.messages.map(msg => {
          if (msg.id === tempId) {
            return {
              ...msg,
              id: response.messageId,
              status: 'sent'
            }
          }
          return msg
        })
        
        this.setData({ messages })
      })
      .catch(error => {
        console.error('发送消息失败:', error)
        
        // 更新消息状态为失败
        const messages = this.data.messages.map(msg => {
          if (msg.id === tempId) {
            return {
              ...msg,
              status: 'failed'
            }
          }
          return msg
        })
        
        this.setData({ messages })
        showError('消息发送失败')
      })
  },

  /**
   * 重新发送失败的消息
   */
  resendMessage(e) {
    const messageId = e.currentTarget.dataset.messageId
    const message = this.data.messages.find(msg => msg.id === messageId)
    
    if (!message) return
    
    // 更新状态为发送中
    const messages = this.data.messages.map(msg => {
      if (msg.id === messageId) {
        return { ...msg, status: 'sending' }
      }
      return msg
    })
    
    this.setData({ messages })
    
    // 重新发送
    this.sendMessage({
      type: message.type,
      content: message.content,
      duration: message.duration
    })
  },

  /**
   * 输入框内容变化
   */
  onInputChange(e) {
    this.setData({
      inputMessage: e.detail.value
    })
    
    // 发送正在输入状态
    this.sendTypingStatus(true)
  },

  /**
   * 输入框失去焦点
   */
  onInputBlur() {
    // 停止正在输入状态
    this.sendTypingStatus(false)
  },

  /**
   * 发送正在输入状态
   */
  sendTypingStatus(isTyping) {
    if (this.data.isTyping === isTyping) return
    
    this.setData({ isTyping })
    
    post('/api/messages/typing-status', {
      conversationId: this.data.conversationId,
      isTyping
    }).catch(error => {
      console.error('发送输入状态失败:', error)
    })
  },

  /**
   * 开始录音
   */
  startRecording() {
    wx.authorize({
      scope: 'scope.record'
    }).then(() => {
      const recorderManager = wx.getRecorderManager()
      
      recorderManager.start({
        duration: 60000, // 最长60秒
        sampleRate: 16000,
        numberOfChannels: 1,
        encodeBitRate: 96000,
        format: 'mp3'
      })
      
      this.setData({
        isRecording: true,
        recordingTime: 0
      })
      
      // 开始计时
      const timer = setInterval(() => {
        this.setData({
          recordingTime: this.data.recordingTime + 1
        })
      }, 1000)
      
      this.setData({ recordingTimer: timer })
      
      // 录音结束事件
      recorderManager.onStop((res) => {
        this.setData({
          isRecording: false,
          voiceFilePath: res.tempFilePath
        })
        
        clearInterval(this.data.recordingTimer)
        
        // 发送语音消息
        this.sendVoiceMessage(res.tempFilePath, this.data.recordingTime)
        
        this.setData({
          recordingTime: 0,
          voiceFilePath: ''
        })
      })
      
      // 录音错误事件
      recorderManager.onError((error) => {
        console.error('录音失败:', error)
        this.stopRecording()
        showError('录音失败，请重试')
      })
      
    }).catch(() => {
      showError('需要录音权限才能发送语音消息')
    })
  },

  /**
   * 停止录音
   */
  stopRecording() {
    if (!this.data.isRecording) return
    
    const recorderManager = wx.getRecorderManager()
    recorderManager.stop()
    
    this.setData({ isRecording: false })
    
    if (this.data.recordingTimer) {
      clearInterval(this.data.recordingTimer)
      this.setData({ recordingTimer: null })
    }
  },

  /**
   * 播放语音消息
   */
  playVoiceMessage(e) {
    const filePath = e.currentTarget.dataset.filePath
    const messageId = e.currentTarget.dataset.messageId
    
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.src = filePath
    innerAudioContext.autoplay = true
    
    // 更新播放状态
    const messages = this.data.messages.map(msg => {
      if (msg.id === messageId) {
        return { ...msg, isPlaying: true }
      } else {
        return { ...msg, isPlaying: false }
      }
    })
    
    this.setData({ messages })
    
    innerAudioContext.onEnded(() => {
      // 播放结束，更新状态
      const messages = this.data.messages.map(msg => {
        if (msg.id === messageId) {
          return { ...msg, isPlaying: false }
        }
        return msg
      })
      
      this.setData({ messages })
      innerAudioContext.destroy()
    })
    
    innerAudioContext.onError((error) => {
      console.error('播放语音失败:', error)
      showError('播放失败')
      innerAudioContext.destroy()
    })
  },

  /**
   * 显示表情面板
   */
  showEmojiPanel() {
    this.setData({
      showEmojiPanel: true,
      showVoicePanel: false,
      showIceBreakerPanel: false
    })
  },

  /**
   * 隐藏表情面板
   */
  hideEmojiPanel() {
    this.setData({ showEmojiPanel: false })
  },

  /**
   * 切换表情分类
   */
  switchEmojiCategory(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ currentEmojiCategory: index })
  },

  /**
   * 显示语音面板
   */
  showVoicePanel() {
    this.setData({
      showVoicePanel: true,
      showEmojiPanel: false,
      showIceBreakerPanel: false
    })
  },

  /**
   * 隐藏语音面板
   */
  hideVoicePanel() {
    this.setData({ showVoicePanel: false })
  },

  /**
   * 显示破冰话题面板
   */
  showIceBreakerPanel() {
    this.setData({
      showIceBreakerPanel: true,
      showEmojiPanel: false,
      showVoicePanel: false
    })
  },

  /**
   * 隐藏破冰话题面板
   */
  hideIceBreakerPanel() {
    this.setData({ showIceBreakerPanel: false })
  },

  /**
   * 显示消息操作菜单
   */
  showMessageMenu(e) {
    const messageId = e.currentTarget.dataset.messageId
    const message = this.data.messages.find(msg => msg.id === messageId)
    
    if (!message) return
    
    this.setData({
      showMessageMenu: true,
      selectedMessage: message
    })
  },

  /**
   * 隐藏消息操作菜单
   */
  hideMessageMenu() {
    this.setData({
      showMessageMenu: false,
      selectedMessage: null
    })
  },

  /**
   * 复制消息
   */
  copyMessage() {
    const message = this.data.selectedMessage
    
    if (message && message.type === 'text') {
      wx.setClipboardData({
        data: message.content,
        success: () => {
          showToast('已复制到剪贴板')
        }
      })
    }
    
    this.hideMessageMenu()
  },

  /**
   * 撤回消息
   */
  recallMessage() {
    const message = this.data.selectedMessage
    
    if (!message || !message.isSelf) {
      showError('只能撤回自己的消息')
      this.hideMessageMenu()
      return
    }
    
    // 检查是否在2分钟内
    const timeDiff = new Date() - new Date(message.createdAt)
    if (timeDiff > 2 * 60 * 1000) {
      showError('超过2分钟无法撤回')
      this.hideMessageMenu()
      return
    }
    
    post('/api/messages/recall', {
      messageId: message.id,
      conversationId: this.data.conversationId
    })
      .then(() => {
        // 更新消息状态
        const messages = this.data.messages.map(msg => {
          if (msg.id === message.id) {
            return {
              ...msg,
              type: 'system',
              content: '你撤回了一条消息',
              isRecalled: true
            }
          }
          return msg
        })
        
        this.setData({ messages })
        showToast('消息已撤回')
      })
      .catch(error => {
        console.error('撤回消息失败:', error)
        showError('撤回失败，请重试')
      })
    
    this.hideMessageMenu()
  },

  /**
   * 滚动到底部
   */
  scrollToBottom() {
    this.setData({ scrollToBottom: true })
    
    setTimeout(() => {
      this.setData({ scrollToBottom: false })
    }, 100)
  },

  /**
   * 标记所有消息为已读
   */
  markAllAsRead() {
    post('/api/messages/mark-read', {
      conversationId: this.data.conversationId
    }).catch(error => {
      console.error('标记已读失败:', error)
    })
  },

  /**
   * 开始消息监听
   */
  startMessageListener() {
    // 模拟实时消息监听
    this.messageListener = setInterval(() => {
      this.checkNewMessages()
    }, 3000)
  },

  /**
   * 停止消息监听
   */
  stopMessageListener() {
    if (this.messageListener) {
      clearInterval(this.messageListener)
      this.messageListener = null
    }
  },

  /**
   * 检查新消息
   */
  checkNewMessages() {
    const lastMessageId = this.data.messages.length > 0 ? 
      this.data.messages[this.data.messages.length - 1].id : ''
    
    get('/api/messages/check-new', {
      conversationId: this.data.conversationId,
      lastMessageId
    })
      .then(data => {
        if (data.newMessages && data.newMessages.length > 0) {
          const newMessages = this.processMessages(data.newMessages)
          
          this.setData({
            messages: [...this.data.messages, ...newMessages]
          })
          
          // 滚动到底部
          this.scrollToBottom()
          
          // 标记为已读
          this.markAllAsRead()
        }
        
        // 更新在线状态
        if (data.userStatus) {
          this.setData({
            isUserOnline: this.checkOnlineStatus(data.userStatus.lastActive),
            lastSeen: this.formatLastSeen(data.userStatus.lastActive)
          })
        }
      })
      .catch(error => {
        console.error('检查新消息失败:', error)
      })
  },

  /**
   * 检查在线状态
   */
  checkOnlineStatus(lastActive) {
    if (!lastActive) return false
    const now = new Date().getTime()
    const lastActiveTime = new Date(lastActive).getTime()
    return (now - lastActiveTime) < 5 * 60 * 1000 // 5分钟内
  },

  /**
   * 格式化最后在线时间
   */
  formatLastSeen(lastActive) {
    if (!lastActive) return '很久以前在线'
    
    const now = new Date().getTime()
    const lastActiveTime = new Date(lastActive).getTime()
    const diff = now - lastActiveTime
    
    const minute = 60 * 1000
    const hour = 60 * minute
    const day = 24 * hour
    
    if (diff < minute) {
      return '刚刚在线'
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前在线'
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前在线'
    } else {
      return Math.floor(diff / day) + '天前在线'
    }
  },

  /**
   * 查看用户资料
   */
  viewUserProfile() {
    navigateTo(`/pages/user-detail/user-detail?userId=${this.data.userId}`)
  },

  /**
   * 分享页面
   */
  onShareAppMessage() {
    return {
      title: '青鸟笺 - 用心灵相遇，让真爱绽放',
      path: '/pages/discovery/discovery',
      imageUrl: '../../images/share-chat.png'
    }
  }
})